package com.wyj.utils

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import com.google.gson.reflect.TypeToken
import com.hjq.gson.factory.GsonFactory
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract

@OptIn(ExperimentalContracts::class)
fun isNullOrEmpty(str: String?): Boolean {
    contract { returns(false) implies (str != null) }
    return str.isNullOrBlank()
}

@OptIn(ExperimentalContracts::class)
fun isNullOrEmpty(list: Array<String>?): Boolean {
    contract { returns(false) implies (list != null) }
    return list.isNullOrEmpty()
}

@OptIn(ExperimentalContracts::class)
fun isNullOrEmpty(list: Collection<*>?): Boolean {
    contract { returns(false) implies (list != null) }
    return list == null || list.isEmpty()
}

inline fun <reified T : Any> T.copy(): T = this.copy {}
inline fun <reified T : Any> T.copy(block: (T) -> Unit): T {
    val t = GsonFactory.getSingletonGson().fromJson<T>(GsonFactory.getSingletonGson().toJson(this), object : TypeToken<T>() {}.type)
    block(t)
    return t
}

fun <T : Activity> Context.asActivity(): T? = when (this) {
    is Activity -> {
        this as? T
    }

    is ContextWrapper -> {
        this.baseContext.asActivity()
    }

    else -> null
}